
// 处理登录相关请求

const md5 = require("../utils/md5");
const email = require("../utils/email");
const response = require("../utils/response");
const config = require('../config');
const dao = require("../dao/user");
const https = require('https');

var identify_codes = {}; // 记录每个邮箱收到的验证码是多少，以及时间

/**
 * 发送验证码
 * @param {*} data {email} 
 */
async function send_identify_code(data) {
    var code = Math.round(Math.random() * 900000 + 100000);
    await email.send_email(data.email, "HSZX-验证码", `【HSZX-树洞】您的验证码为：${code}`);
    identify_codes[data.email] = {code: code, time: new Date()};
}

/**
 * 使用邮箱+验证码登录
 * @param {*} data {email, code}
 * @returns {*} user_info + secret_id
 */
async function loin_by_code(data) {
    if (data.code == identify_codes[data.email].code) {
        if(new Date() - identify_codes[data.email].time < 60000) { //有效期一分钟
            
            var secret_id = md5.hexMD6(data.email);
            var user_id = md5.hexMD6(secret_id);
            var res = await dao.get_user(user_id);
            if (!res) {
                // 新建用户
                await dao.add_user(user_id);
                res = await dao.get_user(user_id);
            }
            res.secret_id = secret_id;
            return response.ok(res);

        } else {
            return response.foridden("验证码失效");
        }
    } else {
        return response.foridden("验证码错误");
    }
}

/**
 * 使用微信登录
 * @param {*} data {wxcode}
 */
async function loin_by_wx(data) {
    var res = await new Promise((resolve, reject) => {
        https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${config.appid}&secret=${config.appsecret}&js_code=${data.wxcode}&grant_type=authorization_code`,
            res => {
                let tmp = '';
                res.on('data', chunk => {
                    tmp += chunk;
                });
                res.on('end', () => {
                    resolve(JSON.parse(tmp));
                });
                res.on('error', e => {
                    reject(e);
                })
            }
        )
    });
    if (res.errcode) {
        return response.forbidden(e.errmsg);
    } else {
        var secret_id = md5.hexMD6(res.openid);
        var user_id = md5.hexMD6(secret_id);
        var res = await dao.get_user(user_id);
        if (!res) {
            // 新建用户
            await dao.add_user(user_id);
            res = await dao.get_user(user_id);
        }
        res.secret_id = secret_id;
        return response.ok(res);
    }
}

/**
 * 使用secret_id登录
 * @param {*} data {secret_id}
 * @returns {*} user_info + secret_id
 */
async function loin_by_sid(data) {
    var user_id = md5.hexMD6(data.secret_id);
    var res = await dao.get_user(user_id);
    if (!res) return response.unacceptable("登录失败：没有找到用户！");
    res.secret_id = data.secret_id;
    return response.ok(res);
}

module.exports = {
    send_identify_code: send_identify_code,
    loin_by_code: loin_by_code,
    loin_by_sid: loin_by_sid,
    loin_by_wx: loin_by_wx,
}
